package com.weirdor.webrtc.ws;

import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import lombok.Data;
import org.tio.server.ServerTioConfig;
import org.tio.websocket.server.WsServerStarter;

/**
 * @program: webrtc-server
 * @description:
 * @author: weirdor
 * @create: 2022-10-23 18:54
 **/
@Data
public class ImWsServerStarter {

    public static WsServerStarter wsServerStarter;

    public static ServerTioConfig serverTioConfig;

    private static Prop p;

    static void loadConfig() {
        if (p == null) {
            p = PropKit.useFirstFound("webrtc-config-pro.txt", "webrtc-config-dev.txt");
        }
    }

    /**
     * 初始化
     *
     * @param port 端口号
     * @throws Exception
     */
    public static void init(int port) throws Exception {
        long heartbeatTimeout = p.getLong("tio.server.heartbeatTimeout");
        String name = p.get("tio.server.name");

        wsServerStarter = new WsServerStarter(port, ImWsMsgHandler.me);
        serverTioConfig = wsServerStarter.getServerTioConfig();
        serverTioConfig.setName(name);
        serverTioConfig.setHeartbeatTimeout(heartbeatTimeout);
        serverTioConfig.debug = p.getBoolean("tio.server.debug");
//        serverTioConfig.setServerAioListener(ImServerListener.me);
        boolean statEnable = p.getBoolean("tio.server.stat-enable");
        if (statEnable) {
            serverTioConfig.setIpStatListener(ImWsIpStatListener.me);
            serverTioConfig.ipStats.addDurations(IpStatDuration.IPSTAT_DURATIONS);
        }
        wsServerStarter.start();
    }

    public static void start() throws Exception {
        loadConfig();
        int port = p.getInt("tio.server.port");
        init(port);
    }


}
